package com.zwz.crawler.basic;

import com.zwz.constant.Constant;
import com.zwz.entity.InvestmentEmploymentInfo;
import com.zwz.parse.JsonParserUtil;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Slf4j
public class TungeeBranchOfficeQuery {

    public static InvestmentEmploymentInfo startTungeeBranchOfficeQuery(String enterpriseId) throws UnsupportedEncodingException {
        // 请求参数
//        String enterpriseId = "577de19eadf21dc4";
        int start = 0;
        int end = 10;
        InvestmentEmploymentInfo res=null;
        // 构建URL（严格编码参数）
        String encodedId = URLEncoder.encode(enterpriseId, String.valueOf(StandardCharsets.UTF_8));
        String url = "https://sales.tungee.com/api/enterprise/detail/branch-office-page"
                + "?enterprise_id=" + encodedId
                + "&start=" + start
                + "&end=" + end;

        try {
            Connection.Response response = Jsoup.connect(url)
                    .method(Connection.Method.GET)
                    // 设置完整请求头（与浏览器完全一致）
                    .header("authority", "sales.tungee.com")
                    .header("accept", "*/*")
                    .header("accept-encoding", "gzip, deflate, br, zstd")
                    .header("accept-language", "zh-CN,zh;q=0.9")
                    .header("cache-control", "no-cache")
                    .header("pragma", "no-cache")
                    .header("priority", "u=1, i")
                    .header("referer", "https://sales.tungee.com/enterprise-details/577de19eadf21dc4/enterprise-information/basic-information")
                    .header("sec-ch-ua", "\"Not;A=Brand\";v=\"24\", \"Chromium\";v=\"128\"")
                    .header("sec-ch-ua-mobile", "?0")
                    .header("sec-ch-ua-platform", "\"Windows\"")
                    .header("sec-fetch-dest", "empty")
                    .header("sec-fetch-mode", "cors")
                    .header("sec-fetch-site", "same-origin")
                    .header("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36")
                    .header("x-tonxis-pid", "67864ea75f69e05d3b544ca7")
//                    .header("cookie", "_tx_pid=67864ea75f69e05d3b544ca7; __wpkreporterwid_=cc4a07fc-7bb9-40a4-96bc-2cbac34b658f; __last_enter_version=sales; _co_i=6805a5576eceb9637696f09d; _tx_uid=680701dddca941522b77e864; _tx_cid=6805a5576eceb9637696f09d; DISTINCT_ID=b84fe276-099f-4932-92b3-d54b92ae384b; _tx_sid=MTc0NTMwMTE0MzYyMjo4MmQ2OTQ5MTY0NjU2ODNmYjQ5MjlmMjc3NDg5ZDFlZg==; Hm_lvt_f2ee75449fc055cc4dbceb4fe403bea3=1745301094,1745302709; HMACCOUNT=B4E402DF057C895E; SecurityCenterDuId=ImFBSG15RzdPdVdPdCtsWnNGMFVuSXhVPSI.GujnjA.YBo4Zvc8vs4jgEmtioacknOQ9pE; tg_referrer_source=https%3A%2F%2Fcrm.tungee.com%2F; acw_tc=0a47308517453903928703142e006e6527c8b0eb5639732bfa5bd10fc7116d; Hm_lpvt_f2ee75449fc055cc4dbceb4fe403bea3=1745391920; accountCenterSessionId=.eJwlzsFKxDAQgOF3yXkPM5lpkt2b2sWL215WhF7KJJlQS6nQdlUU392i95-P_9v0ZdF1MKdtuenBrK_ZnExbD0PzlbCrn7e27obuAaC9NuPTy_mzebxszXhXXa7d1NRn6sb7wRzMrJr7Vd613976HM2pyLTuYP8HklAoATGCUnaUC5bgUDFr1Fg8eiUJycYMLKzMKSXvhQAsSIIjAPgSKIfAIozkI0mRKnm2qQKSmLmCjNEBB7COMbNasEVpl7Mn3Qdvqy7_My6Arxwkp0nj0VFURrTW7lEaZJ512qMPjebnFzoQVH8.Guoisg.RzmOB8rwO6PiO4JCVkLg_Tn8xTg; doncusSessionId=eyJfZnJlc2giOmZhbHNlLCJ1c2VyX2lkIjoiNjgwNzAxZGRkY2E5NDE1MjJiNzdlODY0In0.Guoi5Q.AOFywnwglpi_2Q4U1QtG1R3vIfE")
                    .header("cookie", Constant.cookies)
                    // 关键配置
                    .ignoreContentType(true)  // 允许非HTML响应
                    .ignoreHttpErrors(true)    // 不抛HTTP错误
                    .maxBodySize(0)           // 禁用响应大小限制
                    .timeout(30000)           // 30秒超时
                    .execute();

            // 结果处理
           log.info("HTTP状态码: " + response.statusCode());
//           //log.info("响应内容:\n" + response.body());
            handleErrorCases(response, enterpriseId);

            //解析
             res = JsonParserUtil.ParseCopmpany(response.body());

        } catch (IOException e) {
            System.err.println("网络请求异常: " + e.getMessage());
            e.printStackTrace();
        }
        return res;
    }

    private static void handleErrorCases(Connection.Response response, String enterpriseId) {
        switch (response.statusCode()) {
            case 401:
                System.err.println("[认证失效] 需要：");
                System.err.println("1. 检查Cookie中的accountCenterSessionId是否最新");
                System.err.println("2. 确认doncusSessionId有效性");
                System.err.println("3. 企业ID格式验证：" + enterpriseId);
                break;

            case 403:
                System.err.println("[权限不足] 可能原因：");
                System.err.println("1. 当前账户无查看分支机构权限");
                System.err.println("2. 分页参数超出许可范围（start-end ≤ 50）");
                break;

            case 404:
                System.err.println("[资源不存在] 检查：");
                System.err.println("1. 企业ID是否存在：" + enterpriseId);
                System.err.println("2. 接口路径是否正确：/api/enterprise/detail/branch-office-page");
                break;

            case 429:
                System.err.println("[请求频繁] 建议：");
                System.err.println("1. 添加3-5秒随机延时");
                System.err.println("2. 使用代理IP池轮换");
                break;

            default:
                if (response.statusCode() != 200) {
                    System.err.println("未知错误码: " + response.statusCode());
                }
        }
    }

    // 参数验证（建议在try前添加）
    private static void validateParams(int start, int end) {
        if (start < 0 || end <= start || (end - start) > 50) {
            throw new IllegalArgumentException("分页参数不合法 start:" + start + " end:" + end);
        }
    }
}